package com.gitee.apanlh.spring.configure.db;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import com.gitee.apanlh.util.check.CheckImport;
import com.gitee.apanlh.util.check.CheckLibrary;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericToStringSerializer;

/**
 * 	配置Redis 序列化
 * 	<br>默认JdkSerializationRedisSerializer
 * 	#mark 需要增加配置
 * 	
 * 	@author Pan
 */
public class RedisConfiguration {
	
	static {
		CheckImport.library(CheckLibrary.SPRING_REDIS);
	}
	
	private RedisConnectionFactory redisConnectionFactory;
	
	/**
	 * 	默认构造函数
	 * 	
	 * 	@author Pan
	 * 	@param 	redisConnectionFactory	连接工厂
	 */
	public RedisConfiguration(RedisConnectionFactory redisConnectionFactory) {
		super();
		this.redisConnectionFactory = redisConnectionFactory;
	}
	
	/**
	 * 	设置Redis 序列化方式
	 * 	
	 * 	@author Pan
	 * 	@return	RedisTemplate
	 */
	@Bean
	public RedisTemplate<String, Object> redisTemplate() {
		RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
		
		// 使用 GenericFastJsonRedisSerializer 替换默认序列化 带默认类全限定名
		GenericFastJsonRedisSerializer genericFastJsonRedisSerializer = new GenericFastJsonRedisSerializer();
		
		// 设置key和value的序列化规则
		redisTemplate.setKeySerializer(new GenericToStringSerializer<>(Object.class));
		redisTemplate.setValueSerializer(genericFastJsonRedisSerializer);
		// 设置hashKey和hashValue的序列化规则
		redisTemplate.setHashKeySerializer(new GenericToStringSerializer<>(Object.class));
		redisTemplate.setHashValueSerializer(genericFastJsonRedisSerializer);
		//redisTemplate.setScriptExecutor(scriptExecutor);
		
		// 设置默认序列化方式
		redisTemplate.setDefaultSerializer(genericFastJsonRedisSerializer);
		//redis开启事务
		//redisTemplate.setEnableTransactionSupport(true);
		//		//redisTemplate.afterPropertiesSet();
		redisTemplate.setConnectionFactory(redisConnectionFactory);
		//	在设置所有 bean 属性并满足BeanFactoryAware 、 ApplicationContextAware等后由包含BeanFactory调用.
		redisTemplate.afterPropertiesSet();
		return redisTemplate;
	}
}
